package vic.sendreceive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketAddress;

public class SendReceiveConnection extends Thread{
	protected Socket socket;
    protected BufferedReader socketIn;
    protected PrintWriter socketOut;
    protected SendReceiveServer server;    
    public SendReceiveConnection(Socket socket, SendReceiveServer server) {
        this.socket = socket;
        this.server = server;        
    }
    public SocketAddress getRemoteAddress() {
        return this.socket.getRemoteSocketAddress();
    }
    public void run() {
        try {
			this.socketIn = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
	        this.socketOut = new PrintWriter(this.socket.getOutputStream(), true);
	        this.server.sendAll(this.getRemoteAddress() + " has connected.");
	        String data = this.socketIn.readLine();
	        while (data != null) {
	        	server.gameView.handleClientRequest(data);
	        	data = this.socketIn.readLine();
	        }
        } catch (IOException e) {
			e.printStackTrace();
		}
    }
    public void send(String msg) {
        this.socketOut.write(msg + "\u0000");
        this.socketOut.flush();       
    }
    protected void finalize() {	 
        try {
			this.socketIn.close();
	        this.socketOut.close();
	        this.socket.close();
        } catch (IOException e) {
			e.printStackTrace();
		}
    }
}
